<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>简单登录测试</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .container {
            background-color: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        input[type="text"], input[type="password"] {
            padding: 10px;
            width: 100%;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .result {
            margin-top: 20px;
            padding: 10px;
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            max-height: 400px;
            overflow-y: auto;
        }
        .success {
            color: green;
        }
        .error {
            color: red;
        }
        .info {
            color: blue;
        }
        .debug {
            font-size: 12px;
            color: #666;
            margin-top: 10px;
            border-top: 1px solid #eee;
            padding-top: 10px;
        }
        pre {
            background-color: #f0f0f0;
            padding: 10px;
            border-radius: 4px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
    </style>
</head>
<body>
    <h1>简单登录测试</h1>
    
    <div class="container">
        <h2>用户登录</h2>
        
        <div>
            <label for="username">用户名：</label>
            <input type="text" id="username" value="admin" placeholder="请输入用户名">
        </div>
        
        <div>
            <label for="password">密码：</label>
            <input type="password" id="password" value="admin123" placeholder="请输入密码">
        </div>
        
        <div style="margin: 10px 0;">
            <button id="loginBtn">登录</button>
            <button id="clearStorageBtn" style="background-color: #666; margin-left: 10px;">清空LocalStorage</button>
        </div>
        
        <div id="result" class="result">
            登录状态将显示在这里...
        </div>
        
        <div id="debugInfo" class="debug">
            <h3>调试信息</h3>
            <pre id="debugLog">调试日志将显示在这里...</pre>
        </div>
    </div>

    <script>
        // DOM元素
        const loginBtn = document.getElementById('loginBtn');
        const clearStorageBtn = document.getElementById('clearStorageBtn');
        const result = document.getElementById('result');
        const debugLog = document.getElementById('debugLog');
        
        // 添加调试日志
        function logDebug(message) {
            const timestamp = new Date().toLocaleString();
            debugLog.innerHTML += `[${timestamp}] ${message}\n`;
            debugLog.scrollTop = debugLog.scrollHeight;
        }
        
        // 显示结果
        function showResult(message, type = 'info') {
            const typeClass = type === 'success' ? 'success' : type === 'error' ? 'error' : 'info';
            result.innerHTML = `<p class="${typeClass}">${message}</p>`;
        }
        
        // 清空LocalStorage
        function clearLocalStorage() {
            localStorage.clear();
            logDebug('已清空LocalStorage');
            showResult('LocalStorage已清空', 'info');
        }
        
        // 检查LocalStorage状态
        function checkLocalStorage() {
            logDebug('检查LocalStorage状态...');
            const token = localStorage.getItem('token');
            if (token) {
                logDebug(`LocalStorage中有token，长度: ${token.length}，点数量: ${(token.match(/\./g) || []).length}`);
                logDebug(`Token前20个字符: ${token.substring(0, 20)}...`);
            } else {
                logDebug('LocalStorage中没有token');
            }
        }
        
        // 登录功能
        function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            // 清空之前的日志
            debugLog.innerHTML = '';
            
            if (!username || !password) {
                showResult('用户名和密码不能为空！', 'error');
                logDebug('用户名或密码为空');
                return;
            }
            
            showResult('正在登录...');
            logDebug(`开始登录，用户: ${username}`);
            logDebug(`密码长度: ${password.length}`);
            
            // 先检查LocalStorage
            checkLocalStorage();
            
            fetch('http://localhost:8080/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username: username,
                    password: password
                })
            })
            .then(response => {
                logDebug(`登录请求返回状态码: ${response.status}`);
                logDebug(`响应头: ${JSON.stringify([...response.headers])}`);
                
                // 检查响应是否为空
                const contentType = response.headers.get('content-type');
                logDebug(`响应类型: ${contentType}`);
                
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error(`响应不是JSON格式: ${contentType}`);
                }
                
                return response.json().then(data => ({ status: response.status, data }));
            })
            .then(({ status, data }) => {
                logDebug(`登录响应数据: ${JSON.stringify(data, null, 2)}`);
                
                if (status === 200 && data.data && data.data.token) {
                    const token = data.data.token;
                    
                    logDebug(`登录成功，token长度: ${token.length}`);
                    logDebug(`token格式检查 - 点数量: ${(token.match(/\./g) || []).length}`);
                    logDebug(`token前20个字符: ${token.substring(0, 20)}...`);
                    logDebug(`token后20个字符: ${token.substring(token.length - 20)}`);
                    
                    // 保存token到localStorage
                    localStorage.setItem('token', token);
                    logDebug('已保存token到localStorage');
                    
                    showResult(`登录成功！欢迎 ${username}`, 'success');
                    
                    // 验证保存是否成功
                    const savedToken = localStorage.getItem('token');
                    logDebug(`保存验证 - token长度: ${savedToken ? savedToken.length : 'null'}`);
                    
                    // 测试使用token访问受保护资源
                    testTokenAccess(token);
                } else {
                    const errorMsg = data.msg || '未知错误';
                    showResult(`登录失败: ${errorMsg}`, 'error');
                    logDebug(`登录失败: ${errorMsg}`);
                    logDebug(`响应状态码: ${status}`);
                }
            })
            .catch(error => {
                showResult(`登录异常: ${error.message}`, 'error');
                logDebug(`登录异常: ${error.message}`);
                logDebug(`错误堆栈: ${error.stack}`);
            });
        }
        
        // 测试token访问受保护资源
        function testTokenAccess(token) {
            logDebug('测试使用token访问受保护资源...');
            
            fetch('http://localhost:8080/auth/userInfo', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => {
                logDebug(`访问userInfo接口状态码: ${response.status}`);
                
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error(`访问失败: ${response.status}`);
                }
            })
            .then(data => {
                logDebug(`访问userInfo成功，响应: ${JSON.stringify(data)}`);
            })
            .catch(error => {
                logDebug(`访问userInfo失败: ${error.message}`);
            });
        }
        
        // 初始化页面
        function init() {
            logDebug('页面已加载，初始化中...');
            checkLocalStorage();
            
            // 绑定事件监听器
            loginBtn.addEventListener('click', login);
            clearStorageBtn.addEventListener('click', clearLocalStorage);
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', init);
    </script>
</body>
</html>